package com.hdoit.ares.logical.brokerage.service.impl;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import com.hdoit.ares.logical.acc.service.IAwardSettingService;
import com.hdoit.ares.logical.brokerage.dao.ICarBrokerageRecordDao;
import com.hdoit.ares.logical.brokerage.model.CarBrokerageRecord;
import com.hdoit.ares.logical.brokerage.model.CarShareBrokerage;
import com.hdoit.ares.logical.brokerage.service.ICarBrokerageRecordService;
import com.hdoit.ares.logical.brokerage.service.ICarShareBrokerageService;
import com.hdoit.ares.logical.cust.model.Customer;
import com.hdoit.ares.logical.cust.service.ICustomerService;
import com.hdoit.ares.logical.insu.model.FanhuaCar;
import com.hdoit.ares.logical.viewmodel.brokerage.CarBrokerageRecordSearch;
import com.hdoit.ares.logical.viewmodel.cust.CustomerSearch;
import com.hdoit.ares.selfcommon.enums.acc.InsuranceType;
import com.hdoit.ares.selfcommon.enums.brokerage.ConfirmState;
import com.hdoit.ares.selfcommon.utils.DistributeWealthUtil;
import com.hdoit.ares.selfcommon.utils.ExpressionUtil;
import com.tennetcn.common.dao.base.impl.SuperService;
import com.tennetcn.common.enums.ModelStatus;
import com.tennetcn.common.message.LoginModel;
import com.tennetcn.common.message.PagerModel;
import com.tennetcn.common.utils.CommonUtils;
import com.tennetcn.common.utils.DateUtils;
/**
 * @author      yujinhui
 * @email       
 * @createtime  2017年12月14日 11:31:46
 * @comment
 */
@Component
public class CarBrokerageRecordServiceImpl extends SuperService<CarBrokerageRecord> implements ICarBrokerageRecordService{
    
	private ICarBrokerageRecordDao carBrokerageRecordDao;
	
	public ICarBrokerageRecordDao getCarBrokerageRecordDao() {
		return carBrokerageRecordDao;
	}
	@Resource
	public void setCarBrokerageRecordDao(ICarBrokerageRecordDao carBrokerageRecordDao) {
		this.carBrokerageRecordDao = carBrokerageRecordDao;
	}
	
	private IAwardSettingService awardSettingService;
	public IAwardSettingService getAwardSettingService() {
		return awardSettingService;
	}
    
	@Resource
	public void setAwardSettingService(IAwardSettingService awardSettingService) {
		this.awardSettingService = awardSettingService;
	}
	
	private ICustomerService customerService;
	public ICustomerService getCustomerService() {
		return customerService;
	}
    
	@Resource
	public void setCustomerService(ICustomerService customerService) {
		this.customerService = customerService;
	}
	
	private ICarShareBrokerageService carShareBrokerageService;
	public ICarShareBrokerageService getCarShareBrokerageService() {
		return carShareBrokerageService;
	}
	@Resource
	public void setCarShareBrokerageService(ICarShareBrokerageService carShareBrokerageService) {
		this.carShareBrokerageService = carShareBrokerageService;
	}
	
	@Override
	public List<CarBrokerageRecord> queryList(CarBrokerageRecordSearch search, PagerModel pagerModel) {
		return carBrokerageRecordDao.queryList(search,pagerModel);
	}

	@Override
	public int queryCount(CarBrokerageRecordSearch search) {
		return carBrokerageRecordDao.queryCount(search);
	}
	@Override
	public boolean updateCarBrokerageRecord(String brokerageId, LoginModel loginModel) {
		CarBrokerageRecord carBrokerageRecord = this.queryModel(brokerageId);
		//避免并发操作
		if(ConfirmState.confirmed.equals(carBrokerageRecord.getConfirmState())){
			return false;
		}
		carBrokerageRecord.setConfirmState(ConfirmState.confirmed);
		carBrokerageRecord.setModelStatus(ModelStatus.update);
		System.err.println("进来之前");
		//确定之后开始分润体系
		if(this.applyChange(carBrokerageRecord)){
			System.err.println("进来了");
			return applyChange(carBrokerageRecord,InsuranceType.Car);
		}
		
		return false;
	}
	
	
	public boolean applyChange(CarBrokerageRecord carBrokerageRecord,String insuranceType) {
		
				double promote,firstShare,secondShare,server,hatch;
				
				String str_tax = awardSettingService.queryModelByHC("tax", insuranceType).getExpression();
				double tax = ExpressionUtil.stringToDouble(str_tax,0.00);
				
				double finalPercent = carBrokerageRecord.getBroPercent() * tax;

				String str_promote = awardSettingService.queryModelByHC("promote", insuranceType).getExpression();
				promote = ExpressionUtil.stringToDouble(str_promote,finalPercent);
				
				String str_firstShare = awardSettingService.queryModelByHC("firstShare", insuranceType).getExpression();
				firstShare = ExpressionUtil.stringToDouble(str_firstShare,finalPercent);
				
				String str_secondShare = awardSettingService.queryModelByHC("secondShare",insuranceType).getExpression();
				secondShare = ExpressionUtil.stringToDouble(str_secondShare,finalPercent);
				
				String str_server = awardSettingService.queryModelByHC("server",insuranceType).getExpression();
				server = ExpressionUtil.stringToDouble(str_server,finalPercent);
				
				String str_hatch = awardSettingService.queryModelByHC("hatch",insuranceType).getExpression();
				hatch = ExpressionUtil.stringToDouble(str_hatch,finalPercent);
		        
		        //得到参与分配奖励的人并且分配奖金
		        List<Customer> customers =  customerService.queryListByBuyer(carBrokerageRecord.getCustomerId());
				customers = DistributeWealthUtil.toDistribute(promote, firstShare, secondShare, server, hatch, customers);
				System.err.println("customers的长度" + customers.size());
				
				int groupNum = carShareBrokerageService.queryMaxGroupNum();
				//将分配的金额插入佣金分配表中
				List<CarShareBrokerage> carShareBrokerages = new ArrayList<CarShareBrokerage>();
				for(Customer customer:customers){
					CarShareBrokerage carShareBrokerage = new CarShareBrokerage();
					carShareBrokerage.setFirstShare(customer.getFirstShare());
					carShareBrokerage.setPromote(customer.getPromote());
					carShareBrokerage.setSecondShare(customer.getSecondShare());
					carShareBrokerage.setServer(customer.getServer());
					carShareBrokerage.setHatch(customer.getHatch());
					carShareBrokerage.setSort(customer.getSord());
					carShareBrokerage.setCarBrokerageId(carBrokerageRecord.getId());
					carShareBrokerage.setConfirmState(ConfirmState.unConfirm);
					carShareBrokerage.setCustomerId(customer.getId());
					carShareBrokerage.setId(CommonUtils.getKeyId());
					carShareBrokerage.setGenerateDate(carBrokerageRecord.getRecordDate());
					
					carShareBrokerage.setGroupNum(groupNum);
					carShareBrokerage.setModelStatus(ModelStatus.add);
					
					carShareBrokerages.add(carShareBrokerage);
				}
				System.err.println("shareBrokerages的长度" + carShareBrokerages.size());
				return carShareBrokerageService.insertListEx(carShareBrokerages) ==  carShareBrokerages.size();
			
		
	}
	@Override
	public CarBrokerageRecord queryByTaskId(String taskId) {	
		return carBrokerageRecordDao.queryByTaskId(taskId);
	}
	@Override
	public HashMap<String,String> queryCarBrokerageRecordForStatistic(CustomerSearch search) {
		HashMap<String,String> map = new HashMap<String,String>();
		
		Calendar now = Calendar.getInstance();
		//获取当前时间
		now.setTime(DateUtils.getCurrent());
		//获取当前月份的天数
		int days = now.getActualMaximum(Calendar.DATE);
		
		for(int i = 1; i <= days; i++){
			map.put(String.valueOf(i),String.valueOf(0));
		}
		
		List<CarBrokerageRecord> carBrokerageRecords =carBrokerageRecordDao.queryCarBrokerageRecordForStatistic(search);
	    
		
			for(CarBrokerageRecord carBrokerageRecord:carBrokerageRecords){
				now.setTime(carBrokerageRecord.getRecordDate());
				String key = "" + now.get(Calendar.DAY_OF_MONTH);
				int value = Integer.valueOf(map.get(key)) + 1;
				map.replace(key, String.valueOf(value));
			}
		
		return map;
	}
	@Override
	public HashMap<String, String> queryCarBrokerageRecordForMoney(CustomerSearch search) {
		HashMap<String,String> map = new HashMap<String,String>();
		
		Calendar now = Calendar.getInstance();
		//获取当前时间
		now.setTime(DateUtils.getCurrent());
		//获取当前月份的天数
		int days = now.getActualMaximum(Calendar.DATE);
		
		for(int i = 1; i <= days; i++){
			map.put(String.valueOf(i),String.valueOf(0));
		}
		
		List<CarBrokerageRecord> carBrokerageRecords =carBrokerageRecordDao.queryCarBrokerageRecordForStatistic(search);
	    
		
			for(CarBrokerageRecord carBrokerageRecord:carBrokerageRecords){
				now.setTime(carBrokerageRecord.getRecordDate());
				String key = "" + now.get(Calendar.DAY_OF_MONTH);
				double value = Double.valueOf(map.get(key)) + carBrokerageRecord.getBizInsureInfo();
				map.replace(key, String.valueOf(value));
			}
		
		return map;
	}
	
	@Override
	public boolean setCarBrokerageRecords(FanhuaCar fanhuaCar){
		CarBrokerageRecord carBrokerageRecord = new CarBrokerageRecord();
		carBrokerageRecord.setId(CommonUtils.getKeyId());
		// 获取总保费
		carBrokerageRecord.setBrokerage(Double.valueOf(fanhuaCar.getTotalPremium()));
		carBrokerageRecord.setRecordDate(DateUtils.getCurrent());
		
		//设置犹豫期
		//获取保单生效日期距离现在的时间
		Date now = DateUtils.getCurrent();
		Calendar nowCalendar = Calendar.getInstance();
		Calendar startDateCalendar = Calendar.getInstance();
		nowCalendar.setTime(now);
		startDateCalendar.setTime(fanhuaCar.getBizInsureInfoStartDate());
		Integer day = DateUtils.getDaysBetween(nowCalendar, startDateCalendar);
		if(day>10){
			carBrokerageRecord.setHeisitateDate(10);;
		}else{
			carBrokerageRecord.setHeisitateDate(day);;
		}
		
		carBrokerageRecord.setCustomerId(fanhuaCar.getCustomerId());
		carBrokerageRecord.setCurrency("元");
		carBrokerageRecord.setCompanyName(fanhuaCar.getPrvName());
		carBrokerageRecord.setCarNo(fanhuaCar.getCarLicenseNo());
		carBrokerageRecord.setCarOwnerName(fanhuaCar.getCarOwnerName());
		carBrokerageRecord.setCarName(fanhuaCar.getVehicleName());

		// 投保人姓名电话
		carBrokerageRecord.setApplicantName(fanhuaCar.getApplicantName());
		carBrokerageRecord.setApplicantPhone(fanhuaCar.getCarOwnerPhone());

		// 车辆性质，交强险保单号，商业险保单号，任务号
		carBrokerageRecord.setCarProperty(fanhuaCar.getCarProperty());
		carBrokerageRecord.setEfcInsureInfoPolicyNo(fanhuaCar.getEfcInsureInfoPolicyNo());
		carBrokerageRecord.setBizInsureInfoPolicyNo(fanhuaCar.getBizInsureInfoPolicyNo());
		carBrokerageRecord.setTaskId(fanhuaCar.getTaskId());

		carBrokerageRecord.setConfirmState(ConfirmState.unConfirm);
		String carInsurancePremium = fanhuaCar.getEfcInsureInfoPremium();
		String carInsuranceTaxFee = fanhuaCar.getTaxInsureInfoTaxFee();
		String carInsuranceLateFee = fanhuaCar.getTaxInsureInfoLateFee();
		if (!StringUtils.isEmpty(carInsurancePremium)||!StringUtils.isEmpty(carInsuranceTaxFee) || !StringUtils.isEmpty(carInsuranceLateFee)) {
			carBrokerageRecord.setEfcInsureInfo(Double.valueOf(carInsurancePremium)+Double.valueOf(carInsuranceTaxFee) + Double.valueOf(carInsuranceLateFee));
		}
		String bizInsureInfoPremium = fanhuaCar.getBizInsureInfoPremium();
		if (!StringUtils.isEmpty(bizInsureInfoPremium)) {
			carBrokerageRecord.setBizInsureInfo(Double.valueOf(bizInsureInfoPremium));
		}
		carBrokerageRecord.setModelStatus(ModelStatus.add);
		if(!applyChange(carBrokerageRecord)){
			throw new RuntimeException("carBrokerageRecord save error");
		};
		return true;
	}
}
